package com.oneandseven.dajia.filter;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class AuthorizationFilter extends OncePerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(AuthorizationFilter.class);

    private final StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Value("${spring.profiles.active}")
    private String environment;

    @Autowired
    public AuthorizationFilter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (environment.equals("dev")){
            request.setAttribute("openid", "123");
            request.setAttribute("uid", 1);
            filterChain.doFilter(request, response);
            return;
        }
        if(request.getRequestURI().equals("/api/login")){
            filterChain.doFilter(request, response);
            return;
        }
        if(request.getRequestURI().equals("/helloworld") || request.getRequestURI().equals("/api/listComment")){
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");
        LOG.info("authorizationHeader: " + token);
        if (token == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        String tinfo = stringRedisTemplate.opsForValue().getAndExpire(token, 60 * 60 * 2, TimeUnit.SECONDS);
        if (tinfo == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        String openid = objectMapper.readTree(tinfo).get("openid").asText();
        Long uid = objectMapper.readTree(tinfo).get("uid").asLong();
        LOG.info("filter openid: " + openid + ", uid: " + uid);
        request.setAttribute("openid", openid);
        request.setAttribute("uid", uid);
        filterChain.doFilter(request, response);
    }
}